package com.wnhz.work.yz.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.AddProductBean;
import com.wnhz.work.yz.bean.ProductBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import java.util.ArrayList;
import java.util.List;

public class SelectProductActivity extends BaseActivity implements View.OnClickListener {
    private SwipeMenuListView product;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_product);
        initData();
        initTitle();
        initView();
        showDialog();
        upload();

    }

    private int isLook = 0;

    private void initData() {
        if (getIntent().getSerializableExtra("data") != null)
            str = (List<ProductBean>) getIntent().getSerializableExtra("data");
        isLook = getIntent().getIntExtra("isLook", 0);
        //Log.e("---", str.toString());
    }

//    private String url = "";

    private void upload() {

        XUtil.Post(Url.API_RECORDTYPE, null, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                AddProductBean url = gson.fromJson(result, AddProductBean.class);
                info = (ArrayList<AddProductBean.InfoEntity>) url.getInfo();
                for (int i = 0; i < info.size(); i++) {
                    infoStr.add(info.get(i).getBigclass());
                    infoId.add(info.get(i).getBigclassid());
                    List<String> b = new ArrayList<>();
                    List<String> b2 = new ArrayList<>();
                    for (int j = 0; j < info.get(i).getDetail().size(); j++) {
                        b.add(info.get(i).getDetail().get(j).getClassname());
                        b2.add(info.get(i).getDetail().get(j).getClassid());
                    }
                    detailId.add(b2);
                    detailStr.add(b);
                }
                for (int i = 0; i < info.size(); i++) {
                    List<List<String>> s = new ArrayList<>();
                    List<List<String>> s2 = new ArrayList<>();
                    s.clear();
                    s2.clear();
                    for (int j = 0; j < info.get(i).getDetail().size(); j++) {
                        List<String> l = new ArrayList<>();
                        List<String> l2 = new ArrayList<>();
                        for (int k = 0; k < info.get(i).getDetail().get(j).getDetail_goods().size(); k++) {
                            l.add(info.get(i).getDetail().get(j).getDetail_goods().get(k).getGoods_name());
                            l2.add(info.get(i).getDetail().get(j).getDetail_goods().get(k).getGoods_id());
                        }
                        s.add(l);
                        s2.add(l2);
                    }
                    detail_goodsStr.add(s);
                    detail_goodsId.add(s2);
                }
            }

            @Override
            public void onFinished() {
                // initOption(1, 0);
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private List<ProductBean> str = new ArrayList<>();
    private MyAdapter mAdapter;

    private void initView() {
        product = (SwipeMenuListView) findViewById(R.id.product);
        product.setFlag(true);
        mAdapter = new MyAdapter(str);
        product.setAdapter(mAdapter);

        SwipeMenuCreator creater = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {


                //同理create删除item
                SwipeMenuItem deleteItem = new SwipeMenuItem(SelectProductActivity.this);
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set item title
                deleteItem.setTitle("删除");
                // set item title fontsize
                deleteItem.setTitleSize(12);
                // set item title font color
                deleteItem.setTitleColor(Color.WHITE);
                // set a icon
                //   deleteItem.setIcon(R.mipmap.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        if (isLook == 0) {
            product.setMenuCreator(creater);
            product.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                    switch (index) {

                        case 0:
                            //删除的逻辑
                            showDialogv7("确定删除该件商品吗？", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    str.remove(position);
                                    mAdapter.notifyDataSetChanged();
                                }
                            });
                            break;

                        default:
                            break;
                    }
                    return false;
                }
            });
        }

        mAdapter.notifyDataSetChanged();
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    class MyAdapter extends BaseAdapter {
        private List<ProductBean> str = new ArrayList<>();

        public MyAdapter(List<ProductBean> str) {
            this.str = str;
        }

        @Override
        public int getCount() {
            return str.size();
        }

        @Override
        public Object getItem(int position) {
            return str.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = View.inflate(SelectProductActivity.this, R.layout.item_select_product, null);
                holder.textView = (TextView) convertView.findViewById(R.id.text);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            holder.textView.setText(str.get(position).getInfoStr() + " " + str.get(position).getDetailStr() + " " + str.get(position).getDetail_goodsStr() + " " + str.get(position).getNumber());
            if (isLook == 0)
                holder.textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initOption(2, position);
                        option.show();
                    }
                });
            return convertView;
        }

        class Holder {
            TextView textView;
        }
    }

    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("选择产品");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("保存");
        if (isLook == 0) {
            submit.setVisibility(View.VISIBLE);
            findViewById(R.id.add_product).setOnClickListener(this);
            submit.setOnClickListener(this);
        } else {
            findViewById(R.id.add_product).setVisibility(View.GONE);
        }


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                Intent intent = new Intent();
                ArrayList<ProductBean> data = (ArrayList<ProductBean>) str;
                intent.putExtra("data", data);
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.add_product:
                initOption(1, 0);
                option.show();

                break;
        }
    }

    private OptionsPickerView option;
    private ArrayList<String> infoStr = new ArrayList<>();
    private ArrayList<List<String>> detailStr = new ArrayList<>();
    private ArrayList<List<List<String>>> detail_goodsStr = new ArrayList<>();
    private ArrayList<String> infoId = new ArrayList<>();
    private ArrayList<List<String>> detailId = new ArrayList<>();
    private ArrayList<List<List<String>>> detail_goodsId = new ArrayList<>();

    private ArrayList<AddProductBean.InfoEntity> info;

    private void initOption(final int type, final int position) {

        option = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                final ProductBean bean = new ProductBean();
                bean.setInfoStr(infoStr.get(options1));
                bean.setDetailStr(detailStr.get(options1).get(option2));
                bean.setDetail_goodsStr(detail_goodsStr.get(options1).get(option2).get(options3));
                bean.setInfoId(infoId.get(options1));
                bean.setDetailId(detailId.get(options1).get(option2));
                bean.setDetail_goodsId(detail_goodsId.get(options1).get(option2).get(options3));
//
                AlertDialog.Builder builder = new AlertDialog.Builder(SelectProductActivity.this);
                final View view = View.inflate(SelectProductActivity.this, R.layout.dialog_product, null);
                Button start_time_close = (Button) view.findViewById(R.id.start_time_close);
                builder.setView(view);
                final AlertDialog show = builder.show();
                Window dialogWindow = show.getWindow();
                WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                dialogWindow.setGravity(Gravity.CENTER);
                // lp.x = 100; // 新位置X坐标
                dialogWindow.setAttributes(lp);
                final EditText edit = (EditText) view.findViewById(R.id.edit);

                start_time_close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            bean.setNumber(Integer.parseInt(edit.getText().toString()));
                        } catch (Exception e) {
                            bean.setNumber(1);
                            edit.setText("1");
                        }
                        show.dismiss();
                        if (type == 1) {
                            //添加
                            str.add(bean);
                        } else {
                            //替换
                            str.set(position, bean);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                });


            }
        }).build();
        try {
            option.setPicker(infoStr, detailStr, detail_goodsStr);
        } catch (Exception e) {
            MyToast("网络连接失败");
            return;
        }
        option.show();
//        option = new OptionsPickerView(this);
//        option.setContent
//        option.setPicker(infoStr, detailStr, detail_goodsStr, true);
//        //  设置是否循环滚动
//        option.setCyclic(false, false, false);
//        // 设置默认选中的三级项目
//        option.setSelectOptions(0, 0, 0);
//        //  监听确定选择按钮
//        option.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int option2, int options3) {
//                //返回的分别是三个级别的选中位置
//                final ProductBean bean = new ProductBean();
//                bean.setInfoStr(infoStr.get(options1));
//                bean.setDetailStr(detailStr.get(options1).get(option2));
//                bean.setDetail_goodsStr(detail_goodsStr.get(options1).get(option2).get(options3));
//                bean.setInfoId(infoId.get(options1));
//                bean.setDetailId(detailId.get(options1).get(option2));
//                bean.setDetail_goodsId(detail_goodsId.get(options1).get(option2).get(options3));
////
//                AlertDialog.Builder builder = new AlertDialog.Builder(SelectProductActivity.this);
//                final View view = View.inflate(SelectProductActivity.this, R.layout.dialog_product, null);
//                Button start_time_close = (Button) view.findViewById(R.id.start_time_close);
//                builder.setView(view);
//                final AlertDialog show = builder.show();
//                Window dialogWindow = show.getWindow();
//                WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//                dialogWindow.setGravity(Gravity.CENTER);
//                // lp.x = 100; // 新位置X坐标
//                lp.width = getWindowManager().getDefaultDisplay().getWidth() - 100; // 宽度
//                lp.height = getWindowManager().getDefaultDisplay().getHeight() / 3; // 高度
//                dialogWindow.setAttributes(lp);
//                final EditText edit = (EditText) view.findViewById(R.id.edit);
//                edit.addTextChangedListener(new TextWatcher() {
//                    @Override
//                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//                    }
//
//                    @Override
//                    public void onTextChanged(CharSequence s, int start, int before, int count) {
//                        if (edit.getText().toString().equals("0") || edit.getText().toString().trim().equals("")) {
//                            edit.setText("1");
//                        }
//                    }
//
//                    @Override
//                    public void afterTextChanged(Editable s) {
//
//                    }
//                });
//                start_time_close.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        try {
//                            bean.setNumber(Integer.parseInt(edit.getText().toString()));
//                        } catch (Exception e) {
//                            bean.setNumber(1);
//                        }
//                        show.dismiss();
//                        if (type == 1) {
//                            //添加
//                            str.add(bean);
//                        } else {
//                            //替换
//                            str.set(position, bean);
//                        }
//                        mAdapter.notifyDataSetChanged();
//                    }
//                });
//
//
//            }
//        });


    }
}
